/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package telsoft.cms_admin.utility;

import com.tamnhat.entity.ContentTemplate;
import com.tamnhat.entity.Product_Content;
import com.telsoft.applet.util.DateUtil;
import com.telsoft.lib.util.DataUtil;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.security.auth.message.callback.PrivateKeyCallback;
import org.primefaces.context.RequestContext;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import telsoft.cms_admin.data.DATA_FormTreeProduct;
import telsoft.cms_admin.entity.ETT_Product;
import telsoft.cms_admin.entity.ETT_TreeProduct;
import telsoft.cms_admin.util.BaseController;
import telsoft.util.StringUtil;

/**
 *
 * @author hoannc
 */
@ManagedBean(name = "treeProduct")
@ViewScoped
public class FUNC_FormTreeProduct extends BaseController implements Serializable {

    private ETT_Product selectedRow;
    private ETT_Product ETT_Product;
    private ETT_Product ETT_Product_old;
    private List<ETT_Product> listData = new ArrayList<ETT_Product>();
    private ETT_TreeProduct ETT_Tree;
    private List<ETT_TreeProduct> listUser2Group = new ArrayList<ETT_TreeProduct>();
    private TreeNode root;
    private TreeNode selectedNodes;
    private boolean blSelected = false;
    private List<ETT_TreeProduct> listContentMode = new ArrayList<ETT_TreeProduct>();
    private List<ETT_TreeProduct> listChargingMode = new ArrayList<ETT_TreeProduct>();
    private DATA_FormTreeProduct Model = new DATA_FormTreeProduct();
    private DataModel itemsContent;
    private Product_Content currentPContent;
    private String oldCTId;
    private String ctName;
    private String ctId;
    private Date from_date;
    private Date to_date;
    private boolean renderAdd = false;
    private List<ContentTemplate> listCTNotIn = new ArrayList<ContentTemplate>();
    private ArrayList<ContentTemplate> listCT = new ArrayList<ContentTemplate>();
    private boolean checkClearField = true;

    public FUNC_FormTreeProduct() {
//        super();
        try {
            init();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }

    }

    public boolean isCheckClearField() {
        return checkClearField;
    }

    public void setCheckClearField(boolean checkClearField) {
        this.checkClearField = checkClearField;
    }

    private void init() throws Exception {
        try {

//            listUser2Group = DataUtil.getData(DATA_FormTreeProduct.class, "getUser2Group");
            listUser2Group = Model.getUser2Group();
            ETT_TreeProduct rootTN = new ETT_TreeProduct("Root", "0");
            root = new DefaultTreeNode(rootTN, null);
            // tree 
            buildTree(root);
            root.setExpanded(false);
            ETT_Product = new ETT_Product();
            bDisableModifyRemove = false;
            bFieldEnable = true;
            bDisableAddSearch = true;
            blSelected = false;
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void onNodeSelect(NodeSelectEvent event) {
        if (event == root) {
            bDisableModifyRemove = false;
            bFieldEnable = true;
            bDisableAddSearch = true;
            blSelected = false;
            ETT_Product = new ETT_Product();
            listData = new ArrayList<ETT_Product>();
            selectedRow = new ETT_Product();
        } else {
            try {

                ETT_Tree = (ETT_TreeProduct) event.getTreeNode().getData();
                listContentMode = Model.getListContentMode(ETT_Tree);
                listChargingMode = Model.getListChargingMode(ETT_Tree);
                if (ETT_Tree.getTYPE().equals("1")) {
//                    listData = (List<ETT_Product>) DataUtil.performAction(DATA_FormTreeProduct.class,
//                            "loadDetailProduct", ETT_Tree);
                    listData = Model.loadDetailProduct(ETT_Tree);
                    if (listData.isEmpty()) {
                        bDisableModifyRemove = false;
                        bFieldEnable = true;
                        bDisableAddSearch = false;
                        blSelected = false;
                        ETT_Product = new ETT_Product();
                        listData = new ArrayList<ETT_Product>();
                        selectedRow = new ETT_Product();
                    } else {
                        bDisableModifyRemove = true;
                        bFieldEnable = true;
                        bDisableAddSearch = false;
                        blSelected = true;
                        selectedRow = listData.get(0);
                        ETT_Product = selectedRow;
                    }
                } else {
                    bDisableModifyRemove = false;
                    bFieldEnable = true;
                    bDisableAddSearch = true;
                    blSelected = false;
                    ETT_Product = new ETT_Product();
                    listData = new ArrayList<ETT_Product>();
                }
            } catch (Exception ex) {
                addErrorMessage(ex);
                ex.printStackTrace();
            }
        }
    }

    private void buildTree(TreeNode parent) {
        ETT_TreeProduct treeValue = (ETT_TreeProduct) parent.getData();
        // Add child - group
        for (int i = 0; i < listUser2Group.size(); i++) {
            if (listUser2Group.get(i).getTYPE().equals("0")
                    && listUser2Group.get(i).getPARENT_ID().equals(treeValue.getID())) {
                ETT_TreeProduct rootTN = listUser2Group.get(i);
                TreeNode tmpTN = new DefaultTreeNode(rootTN, parent);
                tmpTN.setExpanded(true);
                buildTree(tmpTN);
            }
        }
        // Add child - user
        for (int i = 0; i < listUser2Group.size(); i++) {
            if (listUser2Group.get(i).getTYPE().equals("1")
                    && listUser2Group.get(i).getPARENT_ID().equals(treeValue.getID())) {
                new DefaultTreeNode(listUser2Group.get(i), parent);
            }
        }
    }

    public void changeState(int iAction, boolean bNormalState) {
        onChangeAction(iAction);
        if (checkClearField) {
            if (bNormalState) {
                bRendered = false;
                bCancel = true;
                bSave = true;
            } else {
                bRendered = true;
                bCancel = false;
                bSave = false;
            }
            setFieldEnable(bNormalState);
            RequestContext.getCurrentInstance().execute("treeblock.hide()");
        }else {
            RequestContext.getCurrentInstance().execute("treeblock.show()");
            bRendered = false;
            bCancel = true;
            bSave = true;
            setFieldEnable(true);
        }
    }

    private void add() {
        try {
            if (validateInput()) {
                ETT_Product.setSERVICE_ID(ETT_Tree.getID());
//                ETT_Product = (ETT_Product) DataUtil.performAction(DATA_FormTreeProduct.class, "insert", ETT_Product);
                ETT_Product = Model.insert(ETT_Product);
                listData.add(ETT_Product);

                //set selected row
                selectedRow = ETT_Product;
                bDisableModifyRemove = true;
            } else {
//                fillDetailValue();
            }
        } catch (Exception ex) {
            addErrorMessage(ex);
//            fillDetailValue();
            ex.printStackTrace();
        }
    }

    private void remove() {
        try {
//            DataUtil.performAction(DATA_FormTreeProduct.class, "delete", selectedRow);
            Model.delete(selectedRow);
            //Update user interface
            listData.remove(selectedRow);

            //set selected row
            if (listData.isEmpty()) {
                bDisableModifyRemove = false;
            } else {
                selectedRow = listData.get(0);
                ETT_Product = selectedRow;
            }
        } catch (Exception ex) {
            addErrorMessage(ex);
            fillDetailValue();
            ex.printStackTrace();
        }
    }

    private void search() {
        try {
//            listData = (List<ETT_Product>) DataUtil.performAction(DATA_FormTreeProduct.class, "search", ETT_Product, ETT_Product);
//            listData = Model.
            //Update UI
            if (listData.isEmpty()) {
                bDisableModifyRemove = false;
                bFieldEnable = true;
                bDisableAddSearch = true;
                blSelected = false;
                listData = new ArrayList<ETT_Product>();
                selectedRow = new ETT_Product();
            } else {
                bDisableModifyRemove = true;
                bFieldEnable = true;
                bDisableAddSearch = false;
                blSelected = true;
                selectedRow = listData.get(0);
                ETT_Product = selectedRow;
            }
        } catch (Exception ex) {
            addErrorMessage(ex);
            fillDetailValue();
            ex.printStackTrace();
        }
    }

    private void modify() {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        try {
            if (validateInput()) {
//                DataUtil.performAction(DATA_FormTreeProduct.class, "update", selectedRow);                     
                Model.update(ETT_Product);
                ETT_Product.setStrCREATED_TIME(df.format(selectedRow.getCREATED_TIME()));
                ETT_Product.setStrEFFECTIVE_TIME(df.format(selectedRow.getEFFECTIVE_TIME()));
                if (selectedRow.getEXPIRY_TIME() == null) {
                    ETT_Product.setStrEXPIRY_TIME(null);
                } else {
                    ETT_Product.setStrEXPIRY_TIME(df.format(selectedRow.getEXPIRY_TIME()));
                }
                //Update user interface
                int i = 0;
                for (ETT_Product item : listData) {
                    if (item.getPRODUCT_ID().equals(ETT_Product.getPRODUCT_ID())) {
                        listData.set(i, ETT_Product);
                        selectedRow = ETT_Product;
                        break;
                    }
                    i++;
                }
            } else {
//                fillDetailValue();
            }
        } catch (Exception ex) {
            addErrorMessage(ex);
//            fillDetailValue();
            ex.printStackTrace();
        }
    }

    public void onRowSelect() {
        try {
            bDisableModifyRemove = true;
            ETT_Product = (ETT_Product) selectedRow.clone();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void onChangeAction(int iOld_Action) {
        if (iOld_Action == ACTION_ADD || iOld_Action == ACTION_SEARCH
                || iOld_Action == ACTION_REMOVE || iOld_Action == ACTION_MODIFY || iOld_Action == ACTION_ADDCOPY) {
            if (iOld_Action == ACTION_ADD) {
                iAction = ACTION_ADD;
                clearFieldValue();
            } else if (iOld_Action == ACTION_MODIFY) {
                iAction = ACTION_MODIFY;
                clearFieldValue();
                fillDetailValue();
            } else if (iOld_Action == ACTION_ADDCOPY) {
                iAction = ACTION_ADDCOPY;
                clearFieldValue();
                fillDetailValue();
            } else if (iOld_Action == ACTION_SEARCH) {
                iAction = ACTION_SEARCH;
                clearFieldValue();
            } else if (iOld_Action == ACTION_REMOVE) {
                iAction = ACTION_REMOVE;
                clearFieldValue();
                doAction();
            }
        } else if (iOld_Action == ACTION_SAVE || iOld_Action == ACTION_CANCEL) {
            if (iOld_Action == ACTION_SAVE) {
                doAction();
            } else if (iOld_Action == ACTION_CANCEL) {
                checkClearField = true;
                fillDetailValue();
            }
        }
    }

    public void fillDetailValue() {
        try {
            ETT_Product = (ETT_Product) ETT_Product_old.clone();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void clearFieldValue() {
        try {
            ETT_Product_old = (ETT_Product) ETT_Product.clone();
            ETT_Product = new ETT_Product();
        } catch (Exception ex) {
            addErrorMessage(ex);
            ex.printStackTrace();
        }
    }

    public void doAction() {
        switch (iAction) {
            case ACTION_ADD:
                add();
                break;
            case ACTION_ADDCOPY:
                add();
                break;
            case ACTION_MODIFY:
                modify();
                break;
            case ACTION_SEARCH:
                search();
                break;
            case ACTION_REMOVE:
                remove();
                break;
        }
    }

    public boolean validateInput() {
        if (StringUtil.nvl(ETT_Product.getSDP_PRODUCT_CODE(), "").equals("")) {
            addErrorMessage("Trường 'Mã hệ thống' không được để trống!");
            checkClearField = false;
            return false;
        }
        if (StringUtil.nvl(ETT_Product.getPRODUCT_NAME(), "").equals("")) {
            addErrorMessage("Trường 'Tên hệ thống' không được để trống!");
            checkClearField = false;
            return false;
        }
        if (StringUtil.nvl(ETT_Product.getREGISTER_KEYWORD(), "").equals("")) {
            addErrorMessage("Trường 'Từ khóa đăng ký' không được để trống!");
            checkClearField = false;
            return false;
        }
        if (StringUtil.nvl(ETT_Product.getCANCEL_KEYWORD(), "").equals("")) {
            addErrorMessage("Trường 'Từ khóa hủy' không được để trống!");
            checkClearField = false;
            return false;
        }
        if (StringUtil.nvl(ETT_Product.getSERVICE_NUMBER(), "").equals("")) {
            addErrorMessage("Trường 'Đầu số dịch vụ' không được để trống và phải nhập theo định dạng XXXX!");
            checkClearField = false;
            return false;
        }
        if (StringUtil.nvl(ETT_Product.getSTATUS(), "").equals("")) {
            addErrorMessage("Trường 'Trạng thái' phải được chọn!");
            checkClearField = false;
            return false;
        }
        if (ETT_Product.getEffective_duration() == 0) {
            addErrorMessage("Trường 'Thời gian dịch vụ' phải là số hoặc lớn hơn 0!");
            checkClearField = false;
            return false;
        }
        checkClearField = true;
        return true;
    }

    public void setFieldEnable(boolean b) {
        if (b) {
            bFieldEnable = false;
        } else {
            bFieldEnable = true;
        }
    }

    public ETT_Product getSelectedRow() {
        return selectedRow;
    }

    public List<ETT_Product> getListData() {
        return listData;
    }

    public void setSelectedRow(ETT_Product selectedRow) {
        this.selectedRow = selectedRow;
    }

    public void setListData(List<ETT_Product> listData) {
        this.listData = listData;
    }

    public ETT_Product getETT_Product() {
        return ETT_Product;
    }

    public void setETT_Product(ETT_Product ETT_Product) {
        this.ETT_Product = ETT_Product;
    }

    public ETT_Product getETT_Product_old() {
        return ETT_Product_old;
    }

    public ETT_TreeProduct getETT_Tree() {
        return ETT_Tree;
    }

    public List<ETT_TreeProduct> getListUser2Group() {
        return listUser2Group;
    }

    public TreeNode getRoot() {
        return root;
    }

    public TreeNode getSelectedNodes() {
        return selectedNodes;
    }

    public void setETT_Product_old(ETT_Product ETT_Product_old) {
        this.ETT_Product_old = ETT_Product_old;
    }

    public void setETT_Tree(ETT_TreeProduct ETT_Tree) {
        this.ETT_Tree = ETT_Tree;
    }

    public void setListUser2Group(List<ETT_TreeProduct> listUser2Group) {
        this.listUser2Group = listUser2Group;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    public void setSelectedNodes(TreeNode selectedNodes) {
        this.selectedNodes = selectedNodes;
    }

    public boolean isBlSelected() {
        return blSelected;
    }

    public void setBlSelected(boolean blSelected) {
        this.blSelected = blSelected;
    }

    public List<ETT_TreeProduct> getListContentBuilderClass() throws Exception {
//        return DataUtil.getData(DATA_FormTreeProduct.class, "getlsContentBuilderClass");
        return Model.getlsContentBuilderClass();
    }

    public List<ETT_TreeProduct> getListChargingClass() throws Exception {
//        return DataUtil.getData(DATA_FormTreeProduct.class, "getlsChargingClass");
        return Model.getlsChargingClass();
    }

    public List<ETT_TreeProduct> getListContentMode() {
        return listContentMode;
    }

    public List<ETT_TreeProduct> getListChargingMode() {
        return listChargingMode;
    }

    public Product_Content getCurrentPContent() {
        return currentPContent;
    }

    public void setCurrentPContent(Product_Content currentPContent) {
        this.currentPContent = currentPContent;
    }

    public String getOldCTId() {
        return oldCTId;
    }

    public void setOldCTId(String oldCTId) {
        this.oldCTId = oldCTId;
    }

    public String getCtName() {
        return ctName;
    }

    public void setCtName(String ctName) {
        this.ctName = ctName;
    }

    public Date getFrom_date() {
        return from_date;
    }

    public void setFrom_date(Date from_date) {
        this.from_date = from_date;
    }

    public Date getTo_date() {
        return to_date;
    }

    public void setTo_date(Date to_date) {
        this.to_date = to_date;
    }

    public ArrayList<ContentTemplate> getListCT() {
        return listCT;
    }

    public void setListCT(ArrayList<ContentTemplate> listCT) {
        this.listCT = listCT;
    }

    public String getCtId() {
        return ctId;
    }

    public void setCtId(String ctId) {
        this.ctId = ctId;
    }

    public boolean isRenderAdd() {
        return renderAdd;
    }

    public void setRenderAdd(boolean renderAdd) {
        this.renderAdd = renderAdd;
    }

    public List<ContentTemplate> getListCTNotIn() {
        return listCTNotIn;
    }

    public void setListCTNotIn(List<ContentTemplate> listCTNotIn) {
        this.listCTNotIn = listCTNotIn;
    }

    //code by thangcoder 
    public DataModel getItemsContent() {
        return itemsContent;
    }

    public void setItemsContent(DataModel itemsContent) {
        this.itemsContent = itemsContent;
    }

    public String updateDlgQLContent() {
        try {            
            ETT_Product = (ETT_Product) selectedRow.clone();
            itemsContent = new ListDataModel(DATA_FormTreeProduct.listProductContent(ETT_Product.getSDP_PRODUCT_CODE()));
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(FUNC_FormTreeProduct.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }

    public String updateRemove() {
        currentPContent = (Product_Content) itemsContent.getRowData();
        return "";
    }

    public String removePContent() {
        if (DATA_FormTreeProduct.remove(currentPContent.getId())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Xóa bản ghi thành công!"));
            itemsContent = new ListDataModel(DATA_FormTreeProduct.listProductContent(ETT_Product.getSDP_PRODUCT_CODE()));
        } else {
            addErrorMessage("Xảy ra lỗi trong quá trình xử lí!");
        }
        return "";
    }

    public boolean checkInput() {
        if (from_date == null || from_date.toString().equalsIgnoreCase("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Không được để trống từ ngày!"));
            return false;
        }
        if (to_date != null && !to_date.toString().equalsIgnoreCase("")) {
            if (to_date.compareTo(from_date) < 0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Đến ngày không được nhỏ hơn từ ngày!"));
                return false;
            }
        }
        return true;
    }

    public String updateEdit() {
        try {
            currentPContent = (Product_Content) itemsContent.getRowData();
            oldCTId = currentPContent.getContent_template_name();
            listCT = (ArrayList<ContentTemplate>) ContentTemplate.allCT("");
            ctName = currentPContent.getContent_template_name();
            from_date = DateUtil.toDate(currentPContent.getFrom_date(), "dd-MM-yyyy");
            if (currentPContent.getTo_date() != null && !currentPContent.getTo_date().equalsIgnoreCase("")) {
                to_date = DateUtil.toDate(currentPContent.getTo_date(), "dd-MM-yyyy");
            }
        } catch (Exception e) {
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("ERROR: " + e.getMessage()));
        }
        return "";
    }

    public String updatePContent() {
        if (checkInput() == false) {
            return "";
        }
        Product_Content p = new Product_Content();
        p.setId(currentPContent.getId());
        p.setProduct_name(currentPContent.getProduct_name());
        p.setContent_template_name(ctName);
        p.setFrom_date(StringUtil.format(from_date, "dd-MM-yyyy"));
        if (to_date != null) {
            p.setTo_date(StringUtil.format(to_date, "dd-MM-yyyy"));
        } else {
            p.setTo_date("");
        }
        if (DATA_FormTreeProduct.update(p)) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Cập nhật bản ghi thành công!"));
            itemsContent = new ListDataModel(DATA_FormTreeProduct.listProductContent(ETT_Product.getSDP_PRODUCT_CODE()));
        } else {
            addErrorMessage("Xảy ra lỗi trong quá trình xử lí!");
        }
        return "";
    }

    public String updateInsert() {
        try {
            renderAdd = true;
            listCTNotIn = ContentTemplate.allCTNotIn(ETT_Product.getPRODUCT_ID());
        } catch (Exception e) {
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("ERROR: " + e.getMessage()));
        }
        return "";
    }

    public String closeAdd() {
        renderAdd = false;
        return "";
    }

    public String insertPContent() {
        if (checkInput() == false) {
            return "";
        }
        String pId = ETT_Product.getPRODUCT_ID();
        Product_Content p = new Product_Content();
        p.setFrom_date(StringUtil.format(from_date, "dd-MM-yyyy"));
        if (to_date != null) {
            p.setTo_date(StringUtil.format(to_date, "dd-MM-yyyy"));
        } else {
            p.setTo_date("");
        }

        if (DATA_FormTreeProduct.insertPContent(p, pId, ctId)) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Thêm bản ghi thành công!!"));
            itemsContent = new ListDataModel(DATA_FormTreeProduct.listProductContent(ETT_Product.getSDP_PRODUCT_CODE()));
            renderAdd = false;
        } else {
            addErrorMessage("Xảy ra lỗi trong quá trình xử lí!");
        }
        return "";
    }
}
